//
//  Useraccount.swift
//  DSWeiBo
//
//  Created by H on 16/5/31.
//  Copyright © 2016年 Mr.Lin. All rights reserved.
//

import UIKit
import SVProgressHUD

class Useraccount: NSObject,NSCoding {

    // 用于调用access_token，接口获取授权后的access token
    var access_token: String?
    /// access_token的生命周期，单位是秒数
    var expires_in: NSNumber?{
        didSet{
            expires_Date = NSDate(timeIntervalSinceNow:expires_in!.doubleValue)
            print(expires_Date)
            
            
        }
    }
    
    var expires_Date:NSDate?
    /// 当前授权用户的UID
    var uid: String?
    
    var screen_name:String?
    var avatar_large:String?
    
    override init() {
        
    }
    init(dict:[String:AnyObject]) {
        super.init()
        
//        access_token = dict["access_token"] as? String
//        expires_in = dict["expires_in"] as? NSNumber
//        uid = dict["uid"] as? String
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print(key)
    }
    
    /// 属性列表
    let properties = ["access_token", "expires_in", "uid","screen_name","avatar_large"]
    /// 打印对象信息
    override var description: String {
        get{
        return "\(self.dictionaryWithValuesForKeys(properties))"
        }
    }
    
    /**
     用户是否登录
     */
   class func userLogin() -> Bool {
        return Useraccount.loadAccount() != nil
    }
    
    
    //MARK ： 保存和读取
    /**
     保存授权模型
     */
    
    static let filePath = "account.plist".cache()
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self , toFile: Useraccount.filePath)
    }
   //加载授权模型
    static var account:Useraccount?
    class func loadAccount() -> Useraccount? {
        if account != nil {
            return account
        }
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? Useraccount
        
        //判断授权信息是否过期

        if account?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            return nil
        }
        
        return account
    }
    
    func loadUserInfo(finished:(account:Useraccount?,error:NSError?)->()){
        
        assert(access_token != nil, "没有授权")
        let path = "2/users/show.json"
        let params = ["access_token":access_token!,"uid":uid!]
        
        NetworkTool.shareNetworkTools().GET(path, parameters: params, success: { (_, JSON) in
            print(JSON)
            
            if let dict = JSON as? [String:AnyObject]{
                self.screen_name = dict["screen_name"] as? String
                self.avatar_large = dict["avatar_large"] as? String
                finished(account: self,error: nil)
                return
            }
                finished(account: self,error: nil)

            }) { (_, error) in
                finished(account: nil,error: error)
        }
    }
    
    func encodeWithCoder(aCoder: NSCoder){
        aCoder.encodeObject(access_token,forKey:"access_token")
        aCoder.encodeObject(expires_in,forKey: "expires_in")
        aCoder.encodeObject(uid,forKey: "uid")
        aCoder.encodeObject(expires_Date,forKey: "expires_Date")
        aCoder.encodeObject(screen_name,forKey: "screen_name")
        aCoder.encodeObject(avatar_large,forKey: "avatar_large")
    }
     required init?(coder aDecoder: NSCoder){
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }// NS_DESIGNATED_INITIALIZER
}
